<?php


namespace modules\english;

use constant\migrate\English;
use entity\db\EntityEnglishNotes;
use model\english\EnglishDb;
use modules\es\EnglishEs;

class ArticleReader
{

    public static function read()
    {
        $file = English::ARTICLE_FILE_PATH;

        $file = file_get_contents($file);

        $rows = preg_split("/\[.*\]/", $file);
        $rows = array_values(array_filter($rows));

        preg_match_all("/\[.*\]/", $file, $tags);
        $tags = current($tags);

        $data = [];
        foreach ($tags as $index => $tag) {
            $article = $rows[$index] ?? '';
            if (!$article) continue;
            $title = explode("\r\n", $article);
            $title = array_filter($title);
            $title = current($title);

            $entity = new EntityEnglishNotes();
            $entity->title = $title;
            $entity->main_tag = preg_replace("/[][]/", "", $tag);
            $entity->content = $article;
            $data[] = $entity;
        }

        \model\english\EnglishNotesDb::articleMultipleSave($data);
    }
    /**
     * @param $fileName
     * @param string $style
     * @return false|string[]
     * @throws \Exception
     */
    public static function format($fileName, $style = 'info')
    {
        if (! file_exists($fileName)) throw new \Exception('file not found');
        $content = file_get_contents($fileName);

        $arr = explode("\n", $content);

        $signPattern = '/(?<=\[).+(?=\])/';
        $wordPattern = '/[a-z]\s\[/i';
        $wordReplacePattern = '/^\d+\./i';

        $words = [];
        foreach ($arr as $v) {
            $v = trim($v);
            if (strlen($v) == 0) continue;

            //单词
            $isWord = preg_match($wordPattern, $v);
            if ($isWord) {
                unset($eg);
                $eg = [];
                //分割单词
                $pos = strpos($v, '[');
                $header = mb_substr($v, 0, $pos);
                //替换序号
                $header = preg_replace($wordReplacePattern, '', $header);
                $word = trim($header);
                $words[] = [
                    'word' => $word,
                    'sign' => $sign ?? '',
                    'content' => $v,
                    'eg' => &$eg,
                ];
            } else {
                preg_match($signPattern, $v, $matches);
                $sign = current($matches);
                if ($sign) {
                    //标签匹配
                    unset($matches);
                } else {
                    //例句处理
                    $eg[] = $v;
                }
            }

        }
        return $words;
    }
}